package com.example.demo.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.example.demo.R;
import com.example.demo.bean.BaseBean;
import com.example.demo.bean.User;
import com.example.demo.network.RetrofitFactory;
import com.example.demo.network.service.UserService;

import org.reactivestreams.Publisher;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        UserService userService = RetrofitFactory.createService(UserService.class);

        findViewById(R.id.button1).setOnClickListener(v -> {
            /*userService.getUser(23L)
                    .subscribeOn(Schedulers.io())  // 在io子线程进行网络请求
                    .observeOn(AndroidSchedulers.mainThread())  // 在Android主线程处理结果
                    .subscribe(new Subscriber<BaseBean<User>>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            Log.i(TAG, "1onSubscribe");
                        }

                        @Override
                        public void onNext(BaseBean<User> userBaseBean) {
                            // 获取成功，处理结果
                            Log.i(TAG, "1onNext" + userBaseBean);
                            Toast.makeText(getApplicationContext(), "1成功:" + userBaseBean, Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onError(Throwable t) {
                            // 获取失败
                            Log.i(TAG, "1onError" + t.getMessage(), t);
                            Toast.makeText(getApplicationContext(), "1失败:" + t.getMessage(), Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onComplete() {
                            Log.i(TAG, "1onComplete");
                        }
                    });*/
            // TODO 不知道为什么，上面只执行了onSubscribe
            userService.getUser(23L)
                    .subscribeOn(Schedulers.io())  // 在io子线程进行网络请求
                    .observeOn(AndroidSchedulers.mainThread())  // 在Android主线程处理结果
                    .subscribe(new Consumer<BaseBean<User>>() {
                        @Override
                        public void accept(BaseBean<User> userBaseBean) throws Throwable {
                            Log.i(TAG, "1成功userBaseBean=:" + userBaseBean);
                            Toast.makeText(getApplicationContext(), "1成功:" + userBaseBean, Toast.LENGTH_LONG).show();
                            User user = userBaseBean.getData();
                            Log.i(TAG, "1成功user=:" + user);
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Throwable {
                            Log.i(TAG, "1失败:" + throwable.getMessage(), throwable);
                            Toast.makeText(getApplicationContext(), "1失败:" + throwable.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
        });

        findViewById(R.id.button2).setOnClickListener(v -> {
            userService.getUserList()
                    .subscribeOn(Schedulers.io())  // 在io子线程进行网络请求
                    .observeOn(AndroidSchedulers.mainThread())  // 在Android主线程处理结果
                    .subscribe(new Consumer<BaseBean<List<User>>>() {
                        @Override
                        public void accept(BaseBean<List<User>> userBaseBean) throws Throwable {
                            // 获取成功，处理结果
                            Log.i(TAG, "2成功:" + userBaseBean);
                            Toast.makeText(getApplicationContext(), "2成功:" + userBaseBean, Toast.LENGTH_LONG).show();
                            List<User> userList = userBaseBean.getData();
                            Log.i(TAG, "userList=:" + userList);
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Throwable {
                            // 获取失败
                            Log.i(TAG, "2失败:" + throwable.getMessage(), throwable);
                            Toast.makeText(getApplicationContext(), "2失败:" + throwable.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });

        });

        findViewById(R.id.button3).setOnClickListener(v -> {
            userService.xxx("asrghed")
                    .subscribeOn(Schedulers.io())  // 在io子线程进行网络请求
                    .observeOn(AndroidSchedulers.mainThread())  // 在Android主线程处理结果
                    .subscribe(new Consumer<BaseBean<String>>() {
                        @Override
                        public void accept(BaseBean<String> stringBaseBean) throws Throwable {
                            // 获取成功，处理结果
                            Log.i(TAG, "3成功:" + stringBaseBean);
                            Toast.makeText(getApplicationContext(), "3成功:" + stringBaseBean, Toast.LENGTH_LONG).show();
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Throwable {
                            // 获取失败
                            // 404
                            Log.i(TAG, "3失败:" + throwable.getMessage(), throwable);
                            Toast.makeText(getApplicationContext(), "3失败:" + throwable.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
        });

        // flatMap进行转换，这里flatMap把第一个网络请求的结果BaseBean<Long>转成一个新的被观察者Publisher<BaseBean<User>>，（Flowable实现了Publisher）
        // 这样达成先处理一个网络请求，再根据第一个的结果处理第二个网络请求
        // 可以接多个flatMap达到串行执行的效果
        // 第一个请求出错（比如404），第二个请求也会出错
        findViewById(R.id.button4).setOnClickListener(v -> {
            userService.getId()
                    .flatMap(new Function<BaseBean<Long>, Publisher<BaseBean<User>>>() {
                        @Override
                        public Publisher<BaseBean<User>> apply(BaseBean<Long> longBaseBean) throws Throwable {
                            Log.d(TAG, "4请求1成功：" + longBaseBean);
                            // 处理第一个请求的结果
                            return userService.getUser(longBaseBean.getData());
                        }
                    })
                    .doOnError(new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Throwable {
                            Log.d(TAG, "4请求1出错：");
                        }
                    })
//                    .delay(1, TimeUnit.SECONDS)  // 延迟1秒后再执行
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<BaseBean<User>>() {
                        @Override
                        public void accept(BaseBean<User> userBaseBean) throws Throwable {
                            Log.d(TAG, "4请求2成功：" + userBaseBean);
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Throwable {
                            Log.d(TAG, "4请求2出错：");
                        }
                    });

        });

    }
}